/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bridge;
import java.util.concurrent.Semaphore;
/**
 *
 * @author aureavm
 */
public class Puente {
    
    Semaphore espacio;
    Semaphore ocupado;
    Semaphore espera;
    int cont;
    int cont2;
    int cont3;
    String destino;
    public Puente(){
    this.espacio = new Semaphore(3,true);
    this.ocupado = new Semaphore(1,true);
    this.espera = new Semaphore(1,true);
    this.cont = 0;
    this.cont2 = 0;
    this.cont3 = 0;
    this.destino = "B";
    }
    public void habilitarDestino(){
        switch (this.destino) {
            case "A":
                this.destino = "B";
                break;
            case "B":
                this.destino = "A";
                break;
            default:
                System.out.println("No se pudo cambiar el destino");
                break;
        }
    }
    
    public void pedir(String destino, int id) throws InterruptedException{
       if(this.destino.equals(destino)){
           while(this.cont2 < 1){
               System.out.println("Se Habilito el puente para pasar a la ciudad: " + destino );
               this.ocupado.acquire();
               this.cont2++;
           }
       }else{
           System.out.println("Esta esperando " + id + " que va para " + destino );
           this.ocupado.acquire();
           this.habilitarDestino();
           this.cont2 = 0;
           this.pedir(destino,id);
       }
        
    }
    public void pasar(int id) throws InterruptedException{
        
    if(this.espacio.availablePermits() == 0){
        
        System.out.println("no hay espacio" + id);
    }else{
        
        this.espacio.acquire();
        int tiempoRecorrido = (int) (Math.random()*10);
        Thread.sleep(tiempoRecorrido * 1000);
        this.cont ++;
        System.out.println("Paso " + id );
        
    }
    
    }
    public void liberar(){
        this.espacio.release();
        this.ocupado.release();
    }
    
   
}
